<template>
  <div class='container'>
    <el-dialog :title="title" :visible="dialogFormVisible" @close="closeDialog">
      <el-form :model="form" :rules="rules">
        <el-form-item label="所属学科" label-width="80px" v-if="!this.$route.query.id">
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option v-for="item in subject" :key="item.vlaue" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" label-width="80px" style="width:300px" prop="tagName">
          <el-input v-model="form.tagName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { simple as tags, add, update } from '@/api/hmmm/tags.js'
export default {
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const checkName = (rule, value, cb) => {
      if (this.form.id && this.form.tagName === value) { cb() }
      this.tags.forEach(item => {
        if (item.label === value) {
          return cb(new Error(`${value}标签已存在`))
        }
      })
      cb()
    }
    return {
      form: {
        subjectID: this.$route.query.id || '',
        tagName: ''
      },
      subject: [],
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: ['blur', 'change'] },
          { validator: checkName, trigger: ['blur', 'change'] }
        ]
      },
      tags: [],
      title: ''
    }
  },
  created () {
    this.getSubjectList()
  },
  methods: {
    async getSubjectList () {
      const { data } = await simple()
      // console.log(data)
      this.subject = data
      const res = await tags()
      console.log(res)
      this.tags = res.data
    },
    closeDialog () {
      this.$emit('update:dialogFormVisible', false)
    },
    async onSubmit () {
      if (this.form.id) {
        const res = await update(this.form)
        console.log(res)
        this.$message.success('修改标签成功')
      } else {
        const res = await add(this.form)
        console.log(res)
        this.$message.success('添加标签成功')
      }
      this.closeDialog()
      this.$emit('reload')
    }
  }
}
</script>

<style scoped lang='less'></style>
